package br.usjt.mazerobot.pc.ui;

import br.usjt.mazerobot.commons.comunicacao.Encoder;
import br.usjt.mazerobot.commons.comunicacao.Pacote;
import br.usjt.mazerobot.commons.constante.IdentificadorPacote;
import br.usjt.mazerobot.commons.constante.Status;
import br.usjt.mazerobot.commons.navegacao.Celula;
import br.usjt.mazerobot.commons.navegacao.Mapa;
import br.usjt.mazerobot.pc.ManterMapa;
import br.usjt.mazerobot.pc.comunicacao.Comunicador;
import br.usjt.mazerobot.pc.util.Logger;
import br.usjt.mazerobot.pc.util.PropertiesUtil;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;

public class PainelControle extends javax.swing.JFrame {

    private Color corDeFundo = new JPanel().getBackground();
    //=================== Variaveis do painel de desenho =======================//
    private Graphics grafico;
    // define o tamanho da celula que é apresentada no labirinto
    private int tamanhoCelula = 15;
    // definem o ponto de origem do labirinto
    private int origemPainelX;
    private int origemPainelY;
    //====================== Variaveis de controle =============================//
    private Mapa mapa;
    private ManterMapa manterMapa;
    private Encoder encoder;
    private Comunicador comunicador;
    private Logger logger;
    private StringBuilder log;
    //====================== Variaveis auxiliares= =============================//
    private static final byte SIM = 1;
    private static final byte NAO = 0;
    private boolean conectado = false;
    private HashSet<Celula> listaCelulas = new HashSet<Celula>();

    //============================ Construtor ==================================//
    public PainelControle(Comunicador comunicador) throws IOException {

        this.comunicador = comunicador;
        manterMapa = new ManterMapa();
        encoder = new Encoder();
        logger = new Logger();

        log = new StringBuilder();

        try {
            //Define o estilo da interface grafica
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            logger.erro(ex.getMessage());
        }
        initComponents();
        grafico = painelMapa.getGraphics();

        configuraJanelaPrincipal();
        montaPainelDesenho();

        carregarListaMapas();//busca os mapas salvos

        textoStatus.setVisible(false);
        barraStatus.setVisible(false);

        Properties properties = PropertiesUtil.loadProperties("Configuracao.properties");
        boolean logRemoto = Boolean.parseBoolean(properties.getProperty("log_remoto"));
        if (!logRemoto) {
            scrollPanelLog.setVisible(false);
        }

        sobreFrame.setSize(new Dimension(400, 300));
        sobreFrame.setVisible(false);

        sobreFrame.setLocationRelativeTo(null);

        listaMapas.addMouseListener(new PopClickListener());
    }

    //==========================================================================
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        sobreFrame = new javax.swing.JFrame();
        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        botaoFechar = new javax.swing.JButton();
        rodape = new javax.swing.JPanel();
        barraStatus = new javax.swing.JProgressBar();
        textoStatus = new javax.swing.JLabel();
        campoMensagem = new javax.swing.JLabel();
        painelPrincipal = new javax.swing.JPanel();
        painelVisualiacao = new javax.swing.JPanel();
        opcaoSelecionada = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        scrollPanelLog = new javax.swing.JScrollPane();
        painelLog = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        painelMapa = new javax.swing.JPanel();
        painelMenuLateral = new javax.swing.JPanel();
        painelMenuSelecionado = new javax.swing.JPanel();
        tituloMenuSelecionado = new javax.swing.JLabel();
        menuOpcoes = new javax.swing.JPanel();
        menuOpcoesExploracao = new javax.swing.JPanel();
        sinalBluetooth = new javax.swing.JLabel();
        menuOpcoesControle = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listaMapas = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jToolBar2 = new javax.swing.JToolBar();
        jPanel2 = new javax.swing.JPanel();
        botaoConectar = new javax.swing.JLabel();
        botaoDesconectar = new javax.swing.JLabel();
        botaoContinuar = new javax.swing.JLabel();
        botaoPausar = new javax.swing.JLabel();
        botaoModoObjetivo = new javax.swing.JLabel();
        botaoModoMapeamento = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();

        sobreFrame.setTitle("Sobre");
        sobreFrame.setResizable(false);

        jPanel3.setMinimumSize(new java.awt.Dimension(400, 300));

        jLabel3.setText("Maze Robot");

        jLabel4.setText("Trabalho de Conclusão de Curso");

        jLabel5.setText("Universidade São Judas Tadeu");

        jLabel6.setText("2011");

        jLabel7.setText("Integrantes:");

        jLabel8.setText("Anderson Alexandrino");

        jLabel9.setText("Alcides Lins");

        jLabel10.setText("Bruno Barreto");

        jLabel11.setText("Henrique Carvalho");

        botaoFechar.setText("Fechar");
        botaoFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoFecharActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(163, 163, 163)
                        .addComponent(jLabel3))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(115, 115, 115)
                        .addComponent(jLabel4))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(jLabel5))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(184, 184, 184)
                        .addComponent(jLabel6))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8)
                            .addComponent(jLabel9)
                            .addComponent(jLabel10)
                            .addComponent(jLabel11)))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(159, 159, 159)
                        .addComponent(botaoFechar)))
                .addContainerGap(130, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addGap(12, 12, 12)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addGap(18, 18, 18)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel11)
                .addGap(18, 18, 18)
                .addComponent(botaoFechar)
                .addContainerGap(51, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout sobreFrameLayout = new javax.swing.GroupLayout(sobreFrame.getContentPane());
        sobreFrame.getContentPane().setLayout(sobreFrameLayout);
        sobreFrameLayout.setHorizontalGroup(
            sobreFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        sobreFrameLayout.setVerticalGroup(
            sobreFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MazeRobot");
        setMinimumSize(new java.awt.Dimension(285, 500));

        rodape.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        rodape.setPreferredSize(new java.awt.Dimension(1044, 25));

        textoStatus.setText("Conectando:");

        campoMensagem.setText("Mensagem Informativa");

        javax.swing.GroupLayout rodapeLayout = new javax.swing.GroupLayout(rodape);
        rodape.setLayout(rodapeLayout);
        rodapeLayout.setHorizontalGroup(
            rodapeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rodapeLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(campoMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 459, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 438, Short.MAX_VALUE)
                .addComponent(textoStatus)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(barraStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(115, 115, 115))
        );
        rodapeLayout.setVerticalGroup(
            rodapeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(rodapeLayout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addGroup(rodapeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(rodapeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(textoStatus)
                        .addComponent(campoMensagem))
                    .addComponent(barraStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(rodape, java.awt.BorderLayout.PAGE_END);

        painelPrincipal.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102)));
        painelPrincipal.setLayout(new java.awt.BorderLayout());

        painelVisualiacao.setMaximumSize(new java.awt.Dimension(32767, 300));
        painelVisualiacao.setMinimumSize(new java.awt.Dimension(200, 300));
        painelVisualiacao.setPreferredSize(new java.awt.Dimension(200, 300));

        opcaoSelecionada.setBackground(new java.awt.Color(153, 153, 153));
        opcaoSelecionada.setPreferredSize(new java.awt.Dimension(799, 25));

        jLabel1.setFont(new java.awt.Font("Arial", 1, 15));
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Exploração");

        javax.swing.GroupLayout opcaoSelecionadaLayout = new javax.swing.GroupLayout(opcaoSelecionada);
        opcaoSelecionada.setLayout(opcaoSelecionadaLayout);
        opcaoSelecionadaLayout.setHorizontalGroup(
            opcaoSelecionadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, opcaoSelecionadaLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 972, Short.MAX_VALUE))
        );
        opcaoSelecionadaLayout.setVerticalGroup(
            opcaoSelecionadaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
        );

        painelLog.setColumns(20);
        painelLog.setEditable(false);
        painelLog.setRows(5);
        painelLog.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        scrollPanelLog.setViewportView(painelLog);

        jScrollPane1.setAutoscrolls(true);

        painelMapa.setBackground(new java.awt.Color(255, 255, 255));
        painelMapa.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        painelMapa.setAutoscrolls(true);

        javax.swing.GroupLayout painelMapaLayout = new javax.swing.GroupLayout(painelMapa);
        painelMapa.setLayout(painelMapaLayout);
        painelMapaLayout.setHorizontalGroup(
            painelMapaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1199, Short.MAX_VALUE)
        );
        painelMapaLayout.setVerticalGroup(
            painelMapaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 539, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(painelMapa);

        javax.swing.GroupLayout painelVisualiacaoLayout = new javax.swing.GroupLayout(painelVisualiacao);
        painelVisualiacao.setLayout(painelVisualiacaoLayout);
        painelVisualiacaoLayout.setHorizontalGroup(
            painelVisualiacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelVisualiacaoLayout.createSequentialGroup()
                .addGroup(painelVisualiacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 982, Short.MAX_VALUE)
                    .addComponent(scrollPanelLog, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 982, Short.MAX_VALUE)
                    .addComponent(opcaoSelecionada, javax.swing.GroupLayout.DEFAULT_SIZE, 982, Short.MAX_VALUE))
                .addContainerGap())
        );
        painelVisualiacaoLayout.setVerticalGroup(
            painelVisualiacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelVisualiacaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(opcaoSelecionada, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrollPanelLog, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        painelPrincipal.add(painelVisualiacao, java.awt.BorderLayout.CENTER);

        painelMenuLateral.setMaximumSize(new java.awt.Dimension(32767, 200));
        painelMenuLateral.setPreferredSize(new java.awt.Dimension(250, 200));

        painelMenuSelecionado.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        painelMenuSelecionado.setFont(new java.awt.Font("Tahoma", 1, 13));
        painelMenuSelecionado.setPreferredSize(new java.awt.Dimension(241, 56));

        tituloMenuSelecionado.setFont(new java.awt.Font("Tahoma", 0, 12));
        tituloMenuSelecionado.setIcon(new ImageIcon("./imagens/register_grande.png"));
        tituloMenuSelecionado.setText("Status do Robô");

        javax.swing.GroupLayout painelMenuSelecionadoLayout = new javax.swing.GroupLayout(painelMenuSelecionado);
        painelMenuSelecionado.setLayout(painelMenuSelecionadoLayout);
        painelMenuSelecionadoLayout.setHorizontalGroup(
            painelMenuSelecionadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelMenuSelecionadoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tituloMenuSelecionado, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)
                .addContainerGap())
        );
        painelMenuSelecionadoLayout.setVerticalGroup(
            painelMenuSelecionadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tituloMenuSelecionado, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
        );

        menuOpcoes.setBackground(new java.awt.Color(255, 255, 255));
        menuOpcoes.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEtchedBorder(), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)));
        menuOpcoes.setPreferredSize(new java.awt.Dimension(240, 523));
        menuOpcoes.setLayout(new java.awt.CardLayout());

        menuOpcoesExploracao.setBackground(new java.awt.Color(255, 255, 255));

        sinalBluetooth.setIcon(new ImageIcon("./imagens/sinal_0.png"));
        sinalBluetooth.setText(": Sinal Bluetooth");

        javax.swing.GroupLayout menuOpcoesExploracaoLayout = new javax.swing.GroupLayout(menuOpcoesExploracao);
        menuOpcoesExploracao.setLayout(menuOpcoesExploracaoLayout);
        menuOpcoesExploracaoLayout.setHorizontalGroup(
            menuOpcoesExploracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(menuOpcoesExploracaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sinalBluetooth, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                .addContainerGap())
        );
        menuOpcoesExploracaoLayout.setVerticalGroup(
            menuOpcoesExploracaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(menuOpcoesExploracaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sinalBluetooth, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(74, Short.MAX_VALUE))
        );

        menuOpcoes.add(menuOpcoesExploracao, "card1");

        menuOpcoesControle.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout menuOpcoesControleLayout = new javax.swing.GroupLayout(menuOpcoesControle);
        menuOpcoesControle.setLayout(menuOpcoesControleLayout);
        menuOpcoesControleLayout.setHorizontalGroup(
            menuOpcoesControleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 222, Short.MAX_VALUE)
        );
        menuOpcoesControleLayout.setVerticalGroup(
            menuOpcoesControleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 121, Short.MAX_VALUE)
        );

        menuOpcoes.add(menuOpcoesControle, "card2");

        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Mapas");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
        );

        listaMapas.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(listaMapas);

        javax.swing.GroupLayout painelMenuLateralLayout = new javax.swing.GroupLayout(painelMenuLateral);
        painelMenuLateral.setLayout(painelMenuLateralLayout);
        painelMenuLateralLayout.setHorizontalGroup(
            painelMenuLateralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelMenuLateralLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(painelMenuLateralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                    .addComponent(menuOpcoes, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                    .addComponent(painelMenuSelecionado, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        painelMenuLateralLayout.setVerticalGroup(
            painelMenuLateralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelMenuLateralLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(painelMenuSelecionado, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(menuOpcoes, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
                .addContainerGap())
        );

        painelPrincipal.add(painelMenuLateral, java.awt.BorderLayout.LINE_START);

        getContentPane().add(painelPrincipal, java.awt.BorderLayout.CENTER);

        jPanel1.setPreferredSize(new java.awt.Dimension(800, 72));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jToolBar2.setFloatable(false);

        jPanel2.setPreferredSize(new java.awt.Dimension(1231, 50));

        botaoConectar.setIcon(new ImageIcon("./imagens/conectar.png"));
        botaoConectar.setText("Conectar");
        botaoConectar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        botaoConectar.setOpaque(true);
        botaoConectar.setPreferredSize(new java.awt.Dimension(44, 48));
        botaoConectar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                conectarListener(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                botaoConectarMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                botaoConectarMouseExited(evt);
            }
        });

        botaoDesconectar.setIcon(new ImageIcon("./imagens/desconectar.png"));
        botaoDesconectar.setText("Desconectar");
        botaoDesconectar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        botaoDesconectar.setEnabled(false);
        botaoDesconectar.setOpaque(true);
        botaoDesconectar.setPreferredSize(new java.awt.Dimension(55, 48));
        botaoDesconectar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                desconectarListener(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                botaoDesconectarMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                botaoDesconectarMouseExited(evt);
            }
        });

        botaoContinuar.setIcon(new ImageIcon("./imagens/continuar.png"));
        botaoContinuar.setText("Continuar");
        botaoContinuar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        botaoContinuar.setEnabled(false);
        botaoContinuar.setOpaque(true);
        botaoContinuar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                continuarListener(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                botaoContinuarMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                botaoContinuarMouseExited(evt);
            }
        });

        botaoPausar.setIcon(new ImageIcon("./imagens/pausar.png"));
        botaoPausar.setText("Pausar");
        botaoPausar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        botaoPausar.setEnabled(false);
        botaoPausar.setOpaque(true);
        botaoPausar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                pausarListener(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                botaoPausarMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                botaoPausarMouseExited(evt);
            }
        });

        botaoModoObjetivo.setIcon(new ImageIcon("./imagens/modo_objetivo.png"));
        botaoModoObjetivo.setText("Modo Objetivo");
        botaoModoObjetivo.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        botaoModoObjetivo.setEnabled(false);
        botaoModoObjetivo.setOpaque(true);
        botaoModoObjetivo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                modoObjetivoListener(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                botaoModoObjetivoMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                botaoModoObjetivoMouseExited(evt);
            }
        });

        botaoModoMapeamento.setIcon(new ImageIcon("./imagens/modo_mapeamento.png"));
        botaoModoMapeamento.setText(" Modo Mapeamento");
        botaoModoMapeamento.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        botaoModoMapeamento.setEnabled(false);
        botaoModoMapeamento.setOpaque(true);
        botaoModoMapeamento.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                modoMapeamentoListener(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                botaoModoMapeamentoMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                botaoModoMapeamentoMouseExited(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(botaoConectar, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(botaoDesconectar, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botaoContinuar, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botaoPausar, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botaoModoObjetivo, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botaoModoMapeamento, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(222, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(botaoConectar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(botaoDesconectar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(botaoContinuar, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
            .addComponent(botaoPausar, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
            .addComponent(botaoModoObjetivo, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
            .addComponent(botaoModoMapeamento, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
        );

        jToolBar2.add(jPanel2);

        jPanel1.add(jToolBar2, java.awt.BorderLayout.SOUTH);

        getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);

        jMenu1.setText("Arquivo");
        jMenu1.setIconTextGap(1);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Salvar");
        jMenuItem1.setIconTextGap(0);
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);
        jMenu1.add(jSeparator1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText("Importar...");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem3.setText("Exportar...");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);
        jMenu1.add(jSeparator2);

        jMenuItem4.setText("Sair");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem4);

        menuBar.add(jMenu1);

        jMenu2.setText("Ajuda");

        jMenuItem5.setText("Sobre");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem5);

        menuBar.add(jMenu2);

        setJMenuBar(menuBar);

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void botaoConectarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoConectarMouseEntered

        if (botaoConectar.isEnabled()) {
            botaoConectar.setBackground(new java.awt.Color(187, 189, 199));
            botaoConectar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(15, 8, 147)));
        }
    }//GEN-LAST:event_botaoConectarMouseEntered
    private void botaoConectarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoConectarMouseExited
        botaoConectar.setBackground(null);
        botaoConectar.setBorder(javax.swing.BorderFactory.createLineBorder(corDeFundo));
    }//GEN-LAST:event_botaoConectarMouseExited
    private void botaoContinuarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoContinuarMouseEntered
        if (botaoContinuar.isEnabled()) {
            botaoContinuar.setBackground(new java.awt.Color(187, 189, 199));
            botaoContinuar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(15, 8, 147)));
        }
    }//GEN-LAST:event_botaoContinuarMouseEntered
    private void botaoPausarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoPausarMouseEntered
        if (botaoPausar.isEnabled()) {
            botaoPausar.setBackground(new java.awt.Color(187, 189, 199));
            botaoPausar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(15, 8, 147)));
        }
    }//GEN-LAST:event_botaoPausarMouseEntered
    private void botaoModoObjetivoMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoModoObjetivoMouseEntered
        if (botaoModoObjetivo.isEnabled()) {
            botaoModoObjetivo.setBackground(new java.awt.Color(187, 189, 199));
            botaoModoObjetivo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(15, 8, 147)));
        }
    }//GEN-LAST:event_botaoModoObjetivoMouseEntered
    private void botaoModoMapeamentoMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoModoMapeamentoMouseEntered
        if (botaoModoMapeamento.isEnabled()) {
            botaoModoMapeamento.setBackground(new java.awt.Color(187, 189, 199));
            botaoModoMapeamento.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(15, 8, 147)));
        }
    }//GEN-LAST:event_botaoModoMapeamentoMouseEntered
    private void botaoContinuarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoContinuarMouseExited
        botaoContinuar.setBackground(null);
        botaoContinuar.setBorder(javax.swing.BorderFactory.createLineBorder(corDeFundo));
    }//GEN-LAST:event_botaoContinuarMouseExited
    private void botaoPausarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoPausarMouseExited
        botaoPausar.setBackground(null);
        botaoPausar.setBorder(javax.swing.BorderFactory.createLineBorder(corDeFundo));
    }//GEN-LAST:event_botaoPausarMouseExited
    private void botaoModoObjetivoMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoModoObjetivoMouseExited
        botaoModoObjetivo.setBackground(null);
        botaoModoObjetivo.setBorder(javax.swing.BorderFactory.createLineBorder(corDeFundo));
    }//GEN-LAST:event_botaoModoObjetivoMouseExited
    private void botaoModoMapeamentoMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoModoMapeamentoMouseExited
        botaoModoMapeamento.setBackground(null);
        botaoModoMapeamento.setBorder(javax.swing.BorderFactory.createLineBorder(corDeFundo));
    }//GEN-LAST:event_botaoModoMapeamentoMouseExited
    private void botaoDesconectarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoDesconectarMouseExited
        botaoDesconectar.setBackground(null);
        botaoDesconectar.setBorder(javax.swing.BorderFactory.createLineBorder(corDeFundo));
    }//GEN-LAST:event_botaoDesconectarMouseExited
    private void botaoDesconectarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botaoDesconectarMouseEntered
        if (botaoDesconectar.isEnabled()) {
            botaoDesconectar.setBackground(new java.awt.Color(187, 189, 199));
            botaoDesconectar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(15, 8, 147)));
        }
    }//GEN-LAST:event_botaoDesconectarMouseEntered
    private void conectarListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_conectarListener
        if (botaoConectar.isEnabled()) {
            //desabilita botao
            botaoConectar.setEnabled(false);
            botaoConectar.setBackground(null);
            botaoConectar.setBorder(javax.swing.BorderFactory.createLineBorder(corDeFundo));
            
            limpaPainelDesenho();
            listaMapas.clearSelection();
            mapa = new Mapa();

            new Thread(new Runnable() {

                @Override
                public void run() {
                    textoStatus.setVisible(true);
                    barraStatus.setVisible(true);
                    barraStatus.setIndeterminate(true);
                    log = new StringBuilder();
                    painelLog.setText(log.toString());
                    if (!conectado) {
                        conectado = comunicador.conectar();
                    }

                    textoStatus.setVisible(false);
                    barraStatus.setVisible(false);

                    if (conectado) {
                        if (!aguardaPacote.isAlive()) {
                            new Thread(aguardaPacote).start();
                        }
                        ativarComponentes(botaoDesconectar, botaoModoObjetivo, botaoModoMapeamento);
                        desativarComponentes(botaoConectar, listaMapas);
                        exibeMensagemInfo("Escolha o modo de operação");

                        exibeMensagemSucesso("Conectado!");
                    } else {
                        exibeMensagemErro("Não foi possível conectar ao dispositivo.");
                        botaoConectar.setEnabled(true);
                    }
                }
            }).start();
        }
    }//GEN-LAST:event_conectarListener
    private void desconectarListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_desconectarListener
        if (botaoDesconectar.isEnabled()) {
            if (conectado) {
                Pacote pacote = new Pacote();
                pacote.setCabecalho(IdentificadorPacote.ENCERRAR_MODO_DE_OPERACAO.getCodigo());
                comunicador.enviar(pacote);

                ativarComponentes(botaoConectar, listaMapas);
                desativarComponentes(botaoDesconectar, botaoContinuar, botaoPausar, botaoModoMapeamento, botaoModoObjetivo);

                aguardaPacote.interrupt();
                limparMensagem();
                exibeMensagemSucesso("Desconectado");
            }
        }
    }//GEN-LAST:event_desconectarListener
    private void continuarListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_continuarListener
        if (botaoContinuar.isEnabled()) {
            if (conectado) {
                Pacote pacote = new Pacote();
                pacote.setCabecalho(IdentificadorPacote.CONTINUAR_EXECUCAO.getCodigo());
                comunicador.enviar(pacote);

                ativarComponentes(botaoPausar);
                desativarComponentes(botaoContinuar);

                exibeMensagemInfo("Em execução");
            }
        }
    }//GEN-LAST:event_continuarListener
    private void pausarListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pausarListener
        if (botaoPausar.isEnabled()) {
            if (conectado) {
                Pacote pacote = new Pacote();
                pacote.setCabecalho(IdentificadorPacote.PAUSAR_EXECUCAO.getCodigo());
                comunicador.enviar(pacote);

                ativarComponentes(botaoContinuar);
                desativarComponentes(botaoPausar);

                exibeMensagemInfo("Aguardando...");
            }
        }
    }//GEN-LAST:event_pausarListener
    private void modoObjetivoListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_modoObjetivoListener

        if (botaoModoObjetivo.isEnabled()) {
            if (conectado) {
                Pacote pacote = encoder.codificar(IdentificadorPacote.MODO_DE_OPERACAO_ENCONTRAR_OBJETIVO, 1000);
                comunicador.enviar(pacote);

                //Habilita/Desabilta os botoes relacionados
                ativarComponentes(botaoPausar);
                desativarComponentes(botaoModoObjetivo, botaoModoMapeamento);

                mapa = new Mapa();
                exibeMensagemInfo("Modo ENCONTRAR OBJETIVO Ativado");
            }
        }
    }//GEN-LAST:event_modoObjetivoListener
    private void modoMapeamentoListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_modoMapeamentoListener

        if (botaoModoMapeamento.isEnabled()) {
            if (conectado) {
                Pacote pacote = encoder.codificar(IdentificadorPacote.MODO_DE_OPERACAO_MAPEAMENTO_COMPLETO,1000);
                comunicador.enviar(pacote);

                //Habilita/Desabilta os botoes relacionados
                ativarComponentes(botaoPausar);
                desativarComponentes(botaoModoMapeamento, botaoModoObjetivo);

                mapa = new Mapa();
                exibeMensagemInfo("Modo MAPEAMENTO COMPLETO ativado");
            }
        }
    }//GEN-LAST:event_modoMapeamentoListener

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        limparMensagem();
        if (manterMapa.salvarMapa(mapa)) {
            exibeMensagemSucesso("Salvo com sucesso");
            carregarListaMapas();
        } else {
            exibeMensagemErro(manterMapa.getMensagemErro());
        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        limparMensagem();
        if (manterMapa.exportarMapa(mapa)) {
            exibeMensagemSucesso("Exportado com sucesso");
        } else {
            exibeMensagemErro(manterMapa.getMensagemErro());
        }
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        limparMensagem();
        if (manterMapa.importarMapa()) {
            exibeMensagemSucesso("Importado com sucesso");
            carregarListaMapas();
        } else {
            exibeMensagemErro(manterMapa.getMensagemErro());
        }
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        if (exibePopupConfirmacao("Sair", "Tem certeza que deseja sair?")) {
            System.exit(0);
        }
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        sobreFrame.setVisible(true);
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void botaoFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoFecharActionPerformed
        sobreFrame.setVisible(false);
    }//GEN-LAST:event_botaoFecharActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JProgressBar barraStatus;
    private javax.swing.JLabel botaoConectar;
    private javax.swing.JLabel botaoContinuar;
    private javax.swing.JLabel botaoDesconectar;
    private javax.swing.JButton botaoFechar;
    private javax.swing.JLabel botaoModoMapeamento;
    private javax.swing.JLabel botaoModoObjetivo;
    private javax.swing.JLabel botaoPausar;
    private javax.swing.JLabel campoMensagem;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JList listaMapas;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JPanel menuOpcoes;
    private javax.swing.JPanel menuOpcoesControle;
    private javax.swing.JPanel menuOpcoesExploracao;
    private javax.swing.JPanel opcaoSelecionada;
    private javax.swing.JTextArea painelLog;
    private javax.swing.JPanel painelMapa;
    private javax.swing.JPanel painelMenuLateral;
    private javax.swing.JPanel painelMenuSelecionado;
    private javax.swing.JPanel painelPrincipal;
    private javax.swing.JPanel painelVisualiacao;
    private javax.swing.JPanel rodape;
    private javax.swing.JScrollPane scrollPanelLog;
    private javax.swing.JLabel sinalBluetooth;
    private javax.swing.JFrame sobreFrame;
    private javax.swing.JLabel textoStatus;
    private javax.swing.JLabel tituloMenuSelecionado;
    // End of variables declaration//GEN-END:variables

    private void confirmaVoltaParaInicio() {
        Pacote pacote = new Pacote();
        byte[] dados = pacote.getConteudo();
        if (exibePopupConfirmacao("Retornar", "Deseja que o robô volte para o ponto inicial?")) {
            dados[0] = SIM;
        } else {
            dados[0] = NAO;
        }
        pacote.setCabecalho(IdentificadorPacote.CONFIRMA_VOLTA_PARA_INICIO.getCodigo());
        pacote.setConteudo(dados);
        comunicador.enviar(pacote);
    }
    //============================== Painel De Desenho =========================//

    private void montaPainelDesenho() {
        origemPainelX = painelMapa.getWidth() / 2;
        origemPainelY = painelMapa.getHeight() / 2;
    }

    private void limpaPainelDesenho() {
        grafico = painelMapa.getGraphics();
        painelMapa.paint(grafico);
    }

    private void redesenhar(Mapa mapa) {
        Celula celula = new Celula();
        limpaPainelDesenho();

        if (mapa != null) {
            short[] limites = mapa.getAreaUtilMapa();
            for (short x = limites[0]; x <= limites[1]; x++) {
                for (short y = limites[2]; y <= limites[3]; y++) {
                    celula.setX(x);
                    celula.setY(y);
                    celula.setStatus(mapa.consulta(celula));
                    desenha(celula);
                }
            }
        }
    }

    public void desenha(Pacote pacote) {
        Celula celula = encoder.decodificaCelula(pacote);
        if (celula.getStatus() == Status.OBJETIVO.getCodigo()) {
            exibeMensagemSucesso("O objetivo foi encontrado em [X: " + celula.getX() + "] [Y: " + celula.getY() + "]");
        }
        if(listaCelulas.add(celula)){
            logger.imprime("Total de celulas " + listaCelulas.size());
        }
        desenha(celula);
    }

    private void desenha(Celula celula) {
        mapa.adiciona(celula);
        grafico = painelMapa.getGraphics();
        grafico.setColor(defineCor(celula.getStatus()));

        int x = origemPainelX + (celula.getX() * (tamanhoCelula));
        int y = origemPainelY - (celula.getY() * (tamanhoCelula));

        grafico.fillRect(x, y, tamanhoCelula, tamanhoCelula);
    }

    private Color defineCor(byte status) {
        Status tipoStatus = Status.fromValue(status);
        Color cor;

        switch (tipoStatus) {
            case LIVRE:
                cor = Color.YELLOW;
                break;
            case INCORRETO:
                cor = Color.RED;
                break;
            case BLOQUEIO:
                cor = Color.BLACK;
                break;
            case INTERSECCAO:
                cor = Color.BLUE;
                break;
            case PERCORRIDO:
                cor = Color.GREEN;
                break;
            case OBJETIVO:
                cor = Color.CYAN;
                break;
            default://VAZIO
                cor = Color.WHITE;
                break;
        }
        return cor;
    }

    /**
     * Sobrescreve o metodo paint para manter o desenho
     * toda vez que o painel sofre alguma alteração
     */
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        montaPainelDesenho();
        redesenhar(mapa);
    }

    //=========================== MENSAGENS ===================================//
    private void exibeMensagemSucesso(String msg) {
        if(!msg.trim().isEmpty()){
            JOptionPane.showMessageDialog(null, msg,"Mensagem" ,JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void exibeMensagemErro(String msg) {
        if(!msg.trim().isEmpty()){
            JOptionPane.showMessageDialog(null, msg,"Erro" ,JOptionPane.ERROR_MESSAGE);
        }
    }

    private void exibeMensagemInfo(String msg) {
        campoMensagem.setForeground(Color.BLACK);
        campoMensagem.setText(msg);
    }

    private void limparMensagem() {
        campoMensagem.setText("");
    }

    private boolean exibePopupConfirmacao(String titulo, String mensagem) {
        return (JOptionPane.showConfirmDialog(null, mensagem, titulo, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION);
    }

    //============================= Arquivos ===================================//
    private void carregarListaMapas() {
        DefaultListModel model = new DefaultListModel();
        listaMapas.setModel(model);
        String[] lista = manterMapa.listarMapas();

        for (int i = 0; i < lista.length; i++) {
            model.add(i, lista[i].replace(manterMapa.EXTENSAO, ""));
        }

    }
    //====================== Gerenciamento de Pacotes ==========================//
    private Thread aguardaPacote = new Thread(new Runnable() {

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    Pacote pacote = comunicador.receber();
                    direcionaPacote(pacote);
                } catch (Exception e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    });

    private void direcionaPacote(Pacote pacote) {

        if (pacote != null) {
            IdentificadorPacote id = IdentificadorPacote.fromValue(pacote.getCabecalho());
            switch (id) {
                case CELULA:
                    desenha(pacote);
                    break;

                case AVISO_BATERIA_FRACA:
                    exibeMensagemErro("ATENÇÃO: A BATERIA DO ROBO ESTA FRACA");
                    break;

                case AVISO_OBJETIVO_NAO_ENCONTRADO:
                    exibeMensagemErro("O objetivo não foi encontrado");
                    break;

                case AVISO_MAPEAMENTO_FINALIZADO:
                    exibeMensagemInfo("Operação Finalizada");
                    ativarComponentes(botaoConectar, listaMapas);
                    desativarComponentes(botaoDesconectar, botaoContinuar, botaoPausar, botaoModoMapeamento, botaoModoObjetivo);
                    break;

                case CONFIRMA_VOLTA_PARA_INICIO:
                    confirmaVoltaParaInicio();
                    break;

                case LOG:
                    String linhaLog = logger.exibeLogRemoto(pacote);
                    if (!linhaLog.isEmpty()) {
                        log.append(linhaLog);
                        log.append("\n");
                        painelLog.setText(log.toString());
                        painelLog.setCaretPosition(log.length());
                    }
                    break;

                case SINAL_BLUETOOTH:
                    int intensidadeSinal = encoder.decodificaObjetivo(pacote);
                    atualizaSinalBluetooth(intensidadeSinal);
                    break;

            }
        }
    }

    private void configuraJanelaPrincipal() {
        //Inicia com janela maximizada
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        //popup de confirmacao ao fechar a janela
        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                if (exibePopupConfirmacao("Sair", "Tem certeza que deseja sair?")) {
                    System.exit(0);
                }
            }
        });
    }

    //==============Manipulação dos botões============================
    private void ativarComponentes(JComponent... componentes) {

        for (JComponent component : componentes) {
            component.setEnabled(true);
        }
    }

    private void desativarComponentes(JComponent... componentes) {

        for (JComponent component : componentes) {
            component.setEnabled(false);
        }
    }

//=====Classe interna para abrir popup ao clicar com o botao direito do mouse ==
    class RightClickPopUp extends JPopupMenu {

        JMenuItem abrir;
        JMenuItem renomear;
        JMenuItem exportar;
        JMenuItem excluir;

        public RightClickPopUp() {

            abrir = new JMenuItem("Abrir");
            renomear = new JMenuItem("Renomear");
            exportar = new JMenuItem("Exportar");
            excluir = new JMenuItem("Excluir");

            abrir.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    abrirMapa();
                }
            });

            renomear.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    renomearMapa();
                }
            });

            exportar.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    exportarMapa();
                }
            });

            excluir.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    excluirMapa();
                }
            });

            add(abrir);
            add(renomear);
            add(exportar);
            add(excluir);
        }

        private void abrirMapa() {
            limparMensagem();

            if (listaMapas.getSelectedValue() != null) {
                mapa = manterMapa.carregarMapa(listaMapas.getSelectedValue().toString());
                redesenhar(mapa);
                exibeMensagemSucesso("Carregado o mapa: " + listaMapas.getSelectedValue().toString());
            } else {
                exibeMensagemInfo("Selecione um mapa");
            }
        }

        private void renomearMapa() {
            limparMensagem();
            if (listaMapas.getSelectedValue() != null) {
                if (manterMapa.renomearMapa(listaMapas.getSelectedValue().toString())) {
                    exibeMensagemSucesso("Renomeado com sucesso");
                    carregarListaMapas();
                } else {
                    exibeMensagemErro(manterMapa.getMensagemErro());
                }
            } else {
                exibeMensagemInfo("Selecione um mapa");
            }
        }

        private void exportarMapa() {
            limparMensagem();
            if (manterMapa.exportarMapa(mapa)) {
                exibeMensagemSucesso("Exportado com sucesso");
            } else {
                exibeMensagemErro(manterMapa.getMensagemErro());
            }
        }

        private void excluirMapa() {
            limparMensagem();
            if (listaMapas.getSelectedValue() != null) {
                if (exibePopupConfirmacao("Atenção", "Confirma exclusão?")) {
                    if (manterMapa.excluirMapa(listaMapas.getSelectedValue().toString())) {
                        exibeMensagemSucesso("Excluido com sucesso");
                        carregarListaMapas();
                    } else {
                        exibeMensagemErro("Não foi possível excluir");
                    }
                }
            } else {
                exibeMensagemInfo("Selecione um mapa");
            }
        }
    }

//===== Listener para abrir popup ao clicar com o botao direito do mouse =======
    class PopClickListener extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.isPopupTrigger()) {
                doPop(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                doPop(e);
            }
        }

        private void doPop(MouseEvent e) {
            RightClickPopUp menu = new RightClickPopUp();
            menu.show(e.getComponent(), e.getX(), e.getY());
        }
    }

    //============Controla animação do icone bluetooth===================
    public void atualizaSinalBluetooth(int intensidade){

        double porcentagem = intensidade / 255.0 * 100;

        if(porcentagem <= 0.0){
            sinalBluetooth.setIcon(new ImageIcon("./imagens/sinal_0.png"));
        }else if(porcentagem <= 20.0){
            sinalBluetooth.setIcon(new ImageIcon("./imagens/sinal_1.png"));
        } else if(porcentagem <= 40.0){
            sinalBluetooth.setIcon(new ImageIcon("./imagens/sinal_2.png"));
        } else if(porcentagem <= 60.0){
            sinalBluetooth.setIcon(new ImageIcon("./imagens/sinal_3.png"));
        } else if(porcentagem <= 80.0){
            sinalBluetooth.setIcon(new ImageIcon("./imagens/sinal_4.png"));
        } else {
            sinalBluetooth.setIcon(new ImageIcon("./imagens/sinal_5.png"));
        }
    }
}
